package dao

import (
	"context"

	"go-mall/common/logger"
	"go-mall/config"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var (
	_DbMaster *gorm.DB
	_DbSlave  *gorm.DB
)

func DB() *gorm.DB {
	return _DbMaster
}

func init() {
	_DbMaster = initDB(config.Database.Master)
	_DbSlave = initDB(config.Database.Slave)
}

func initDB(option config.DbConnectOption) *gorm.DB {
	logger.New(context.Background()).Info("database info", "db", option)
	db, err := gorm.Open(mysql.Open(option.DSN), &gorm.Config{})
	if err != nil {
		panic(err)
		// return nil
	}
	sqlDb, _ := db.DB()
	sqlDb.SetMaxOpenConns(option.MaxOpenConn)
	sqlDb.SetMaxIdleConns(option.MaxIdleConn)
	sqlDb.SetConnMaxLifetime(option.MaxLifeTime)

	if err := sqlDb.Ping(); err != nil {
		panic(err)
	}
	return db
}
